const jsonfile = require('jsonfile');
const {flatten,isArray,uniqBy,sortBy} =require('loadsh')
const {setNotify} =require('../util/notify')
const fs=require('fs')
const path = require('path')
const moment =require('moment')
module.exports = {
    '/':(req, res)=>{
        //搜索
        let {code='',name='',tag='',platform}=req.query
        if(!platform) return res.send({code:1,msg:'平台不能为空'});
        tag=tag==='全部'?'':tag
        try {
            const listObject=jsonfile.readFileSync(`data/shop/${platform}.json`);
            const sortValues=sortBy(tag?(listObject[tag] || []):flatten(Object.values(listObject).filter(i=>isArray(i))),item=>item.tag==='全部');
            let values=uniqBy(sortValues,'name');
            const isReady= listObject.isReady
            const isUseName= listObject.type
            const result=values.filter(i=>(isUseName?i.name.includes(name):i.code.includes(code) && i.name.includes(name)) && i.tag.includes(tag))
            res.send({
                code:0,
                data:result,
                msg:'请求成功'
            });
        }catch(err){
            res.send({
                code:0,
                data:[]
            });
        }
    },
    '/getImg':(req, res)=>{
        res.send({code:0,data:global.filelist,msg:'请求成功'});
    },
    '/delImg':(req, res)=>{
        const {path}=req.body
        if(!path) return res.send({code:1,msg:'路径不能为空'});
        try {
            fs.unlinkSync(path);
            const index=global.filelist.findIndex(i=>i.includes(path))
            global.filelist.splice(index,1)
            res.send({code:0,msg:'删除成功'});
        }catch {
            res.send({code:1,msg:'文件不存在'});
        }
    },
    '/upload':(req, res)=>{
        const {sign}=req.body
        if(!sign) return res.send({code:1,msg:'平台不能为空'});
        const filepath = req.file.path
        const time = moment().format('YYYYMMDDHHmmss');
        const extname = path.extname(req.file.originalname)
        const filename = `${sign}_${time}${extname}`
        fs.rename(filepath,path.join(path.dirname(filepath),filename), err =>{
            if(!err){
                global.filelist.push('/assets/upload/shop/'+filename)
                res.send({code:0,data:'/assets/upload/shop/'+filename,msg:'上传成功'});
            }else {
                res.send({code:1,msg:'上传失败'});
            }
        })
    },
    '/startUse':(req, res)=>{
        const {platform,name}=req.body
        if(!platform || !name) return res.send({code:1,msg:'平台不能为空'});
        const platformTags=jsonfile.readFileSync(`data/tag.json`)
        const shopObject=jsonfile.readFileSync(`data/shop/${platform}.json`)
        const time = moment().format('YYYY-MM-DD HH:mm:ss');
        if(!platformTags[`shop_${name}`].isReady){
            const time = moment().format('YYYY-MM-DD HH:mm:ss');
            platformTags[`shop_${name}`].isReady=1
            shopObject.isReady=1
            setNotify(`${time} ${name}`,
                `<p class="notifyContent">商家${name}菜单 <strong>已开始使用</strong> ，可在点餐管理页面 <strong>选择商家并输入CODE</strong> 或者商家管理页面 <strong>点击下单</strong> 进行点餐</p>`,
                global.userList.map(username=>({username})))
        }else {
            setNotify(`${time} ${name}`,
                `<p class="notifyContent">商家${name}菜单 <strong>已取消使用</strong>，可在点餐管理页面 <strong>选择商家并输入CODE，菜名，价格进行点餐</p>`,
                global.userList.map(username=>({username})))
            delete platformTags[`shop_${name}`].isReady
            delete shopObject.isReady
        }
        jsonfile.writeFileSync(`data/tag.json`,platformTags)
        jsonfile.writeFileSync(`data/shop/${platform}.json`,shopObject)
        res.send({
            code: 0,
            msg: platformTags[`shop_${name}`].isReady?'菜单开始使用，订单数据将依据此菜单为准':'菜单取消使用，订单数据将依据管理员审核为准',
        })
        /*const shopObject=jsonfile.readFileSync(`data/shop/${platform}.json`)
        const isReady=shopObject.isReady
        if(!isReady){
            const time = moment().format('YYYY-MM-DD HH:mm:ss');
            shopObject.isReady=1
            // global.notifyList
            setNotify(`${time} ${name}`,
                `<p class="notifyContent">商家${name}菜单 <strong>已开始使用</strong> ，可在点餐管理页面 <strong>选择商家并输入CODE</strong> 或者商家管理页面 <strong>点击下单</strong> 进行点餐</p>`)
        }else {
            setNotify(`${time} ${name}`,
                `<p class="notifyContent">商家${name}菜单 <strong>已取消使用</strong>，可在点餐管理页面 <strong>选择商家并输入CODE，菜名，价格进行点餐</p>`)

            shopObject.isReady=0
        }
        jsonfile.writeFileSync(`data/shop/${platform}.json`,shopObject)
        res.send({
            code: 0,
            msg: shopObject.isReady?'菜单开始使用，订单数据将依据此菜单为准':'菜单取消使用，订单数据将依据管理员审核为准',
        })*/
    },
    '/set':(req, res)=>{
        const {platform,code,tag,name,price}=req.body
        if(!platform) return res.send({code:1,msg:'平台不能为空'});
        const listObject=jsonfile.readFileSync(`data/shop/${platform}.json`)
        if(listObject[tag]){
            let index=listObject[tag].findIndex(i=>i.code===code)
            if(index>-1){
                listObject[tag].splice(index,1,{tag,code,name,price})
            }else {
                listObject[tag].push({tag,code,name,price})
            }
        }else {
            listObject[tag]=[{tag,code,name,price}]
        }
        jsonfile.writeFileSync(`data/shop/${platform}.json`,listObject)
        res.send({
            code: 0,
            msg: '操作成功',
        })
    },
    '/del':(req, res)=>{
        const {platform,tag,code}=req.body
        if(!platform || !tag || !code) return res.send({code:1,msg:'平台、分类和CODE不能为空'});
        const listObject=jsonfile.readFileSync(`data/shop/${platform}.json`)
        if(listObject[tag]){
            const index=listObject[tag].findIndex(i=>i.code.includes(code))
            listObject[tag].splice(index,1)
            if(!listObject[tag].length){
                //彻底删除菜单
                delete listObject[tag]
            }
            jsonfile.writeFileSync(`data/shop/${platform}.json`,listObject)
            res.send({
                code: 0,
                msg: '删除成功',
            })
        }else {
            res.send({
                code: 1,
                msg: '菜单不存在',
            })
        }
    },
}
